package cn.xsirl.websocket.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
import org.springframework.web.socket.server.HandshakeInterceptor;
import org.springframework.web.socket.server.standard.ServletServerContainerFactoryBean;

/**
 * websocket配置
 */
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
    
    /**
     * 注入自定义处理器
     */
    @Autowired
    private WebSocketHandler handler;
    
    /**
     * 自定义拦截器
     */
    @Autowired
    private HandshakeInterceptor interceptor;
    
    /**
     * 注册WebSocket处理器
     */
    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        // 添加自定义处理器，以及对应的映射路径
        registry.addHandler(handler, "/chatroom")
                // 添加自定义拦截器
                .addInterceptors(interceptor);
    }
    
    @Bean
    public ServletServerContainerFactoryBean createWebSocketContainer() {
        ServletServerContainerFactoryBean container = new ServletServerContainerFactoryBean();
        // 设置二进制消息的最大限制
        container.setMaxBinaryMessageBufferSize(10 * 1024 * 1024);
        // 设置文本消息的最大限制
        container.setMaxTextMessageBufferSize(10 * 1024 * 1024);
        return container;
    }
}
